<template>
  <div class="app-container">
 <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="78px">
      <el-form-item label="关键词" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入群助手所属人信息（姓名、手机号）"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属人ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入群助手所属人ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          type="datetime"
          placeholder="选择开始时间"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          type="datetime"
          placeholder="选择结束时间"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['money:groupAssistant:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="groupAssistantList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="群助手ID" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="ownerName" />
         <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isExpired === 0 ? 'danger' : 'success'">
            {{ scope.row.isExpired === 0 ? '过期' : '未过期' }}
          </el-tag>
        </template>
      </el-table-column>
    <el-table-column label="开始时间" align="center" prop="startTime" width="180"/>
    <el-table-column label="结束时间" align="center" prop="endTime" width="180"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['money:groupAssistant:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['money:groupAssistant:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改群助手用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="200px">
        <el-form-item label="群助手所属人" prop="ownerId">
          <el-select 
            v-model="form.ownerId" 
            placeholder="请选择群助手所属人" 
            filterable 
            remote 
            :remote-method="searchUsers" 
            :loading="userLoading" 
            clearable>
            <el-option 
              v-for="user in userOptions" 
              :key="user.uid || user.userId || user.id" 
              :label="user.displayName || user.userName || user.nickName || user.uid" 
              :value="user.id || user.userId || user.uid">
              <span style="float: left; max-width: 30%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ user.displayName || user.userName || user.nickName || user.uid }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px; max-width: 65%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ user.userName || user.uid }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="date"
            placeholder="选择开始时间"
            value-format="yyyy-MM-dd"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="date"
            placeholder="选择结束时间"
            value-format="yyyy-MM-dd"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGroupAssistant, delGroupAssistant, addGroupAssistant } from "@/api/zl/groupAssistant";
import { listUser } from "@/api/zl/user";

export default {
  name: "GroupAssistant",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 群助手用户表格数据
      groupAssistantList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户选项
      userOptions: [],
      // 用户搜索加载状态
      userLoading: false,
        // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        userId: null,
        startTime: null,
        endTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ownerId: [
          { required: true, message: "群助手所属人不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询群助手用户列表 */
    getList() {
      this.loading = true;
      listGroupAssistant(this.queryParams).then(response => {
        this.groupAssistantList = response.rows;
        this.total = parseInt(response.total) || 0;
        this.loading = false;
      });
    },
    /** 搜索用户 */
    searchUsers(query) {
    console.log('searchUsers 被调用，query参数:', query);
      if (query !== '') {
        this.userLoading = true;
        // 使用真实的用户查询API
        const searchParams = {
          pageNum: 1,
          pageSize: 20, // 限制搜索结果数量
          displayName: query, // 根据用户名搜索
          // 可以根据实际API参数调整搜索字段
        };
        
        listUser(searchParams).then(response => {
          this.userOptions = response.rows || response.data || [];
          this.userLoading = false;
        }).catch(error => {
          console.error('搜索用户失败:', error);
          this.userOptions = [];
          this.userLoading = false;
        });
      } else {
        this.userOptions = [];
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ownerId: null,
        startTime: null,
        endTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加群助手用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      // 获取群助手详情并填充表单
      // 这里可以直接使用行数据填充表单
      this.form = {
        id: row.id,
        ownerId: row.ownerId,
        startTime: row.startTime,
        endTime: row.endTime
      };
        // 设置用户选项以便回显用户名称
      if (row.ownerName && row.ownerId) {
        this.userOptions = [{
          id: row.ownerId,
          uid: row.ownerId,
          userId: row.ownerId,
          displayName: row.ownerName,
          userName: row.ownerName,
          nickName: row.ownerName
        }];
      }
      this.open = true;
      this.title = "修改群助手";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 修改时需要传递 ID，新增时不传
          if (this.form.id != null) {
            // 修改操作，调用新增接口但传递 ID
            addGroupAssistant(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增操作
            addGroupAssistant(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除群助手用户编号为"' + ids + '"的数据项？').then(function() {
        return delGroupAssistant(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>

